<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-05
 * Time: 10:52
 */

namespace app\api\controller\v1;


use app\api\model\Admin as AdminModel;
use app\api\model\LinUser;
use think\Db;
use think\Exception;
use think\facade\Request;

class Admin
{
    /**
     * 获取后台全部账号信息除了总管理员
     */
    public function getDataAll()
    {
        return LinUser::where('admin',1)->where('id','neq',57)->select()->toArray();
    }

    /**
     * 获取列表
     * @validate('PagingParameter')
     */
    public function getDataList($page,$limit,$name)
    {
        $query = AdminModel::hasWhere('linUser',function($query) use($name){
            if($name) {
                $query->where('username','like','%'.$name.'%');
            }
        })->order('admin.id desc');
        $count = $query->count();
        $result = $query->page($page, $limit)->select()->each(function ($item){
            $info = LinUser::get($item['lin_user_id']);
            $item['username'] = $info['username'];
        })->toArray();
        $data['count'] = $count;
        $data['data'] = $result;
        return $data;
    }

    /**
     * 获取详情
     * @validate('IdMustBePositiveInt')
     * @auth('门店信息','门店信息设置')
     */
    public function getDataInfo($id)
    {
        return AdminModel::with('img')->where('lin_user_id',$id)->find();
    }

    /**
     * 添加或修改
     * @validate('checkAdmin')
     * @auth('编辑信息','门店信息设置')
     */
    public function createUpdateData()
    {
        $data = Request::post();
        $admin = AdminModel::where('lin_user_id',$data['lin_user_id'])->find();
        if($admin) {
            Db::startTrans();
            try{
                $mode = new AdminModel();
                $mode->allowField(true)->save($data,['id',$data['id']]);
                //事务结束  开始到结束中间出现错误以后,先执行的添加就不会生成记录
                Db::commit();
                return writeJson(202, [], '修改成功！');
            }
            catch (Exception $ex){
                Db::rollback();
                throw $ex;
            }
        } else {
            Db::startTrans();
            try{
                AdminModel::create($data);
                Db::commit();
                return writeJson(201, [], '添加成功！');
            }
            catch (Exception $ex){
                Db::rollback();
                throw $ex;
            }
        }
    }
}